//
//  SJNetworkHelper.m
//  SJDFBackstage
//
//  Created by armada on 2018/1/22.
//  Copyright © 2018年 Leon Guo. All rights reserved.
//

#import "SJNetworkHelper.h"

AFHTTPSessionManager *_manager;

#define BASE_URL @"http://cms.chinacampus.org"
#define SHOPING_URL @"http://api.chinacampus.org"
#define APIKEY @"6de9cc05-6c46-4e29-84f3-a638e442465a"

@implementation SJNetworkHelper

+(instancetype)sharedManager {

    static SJNetworkHelper *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!sharedManager) {
           sharedManager = [[SJNetworkHelper alloc] init];
        }
    });
    return sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _manager = [AFHTTPSessionManager manager];
        [_manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    }
    return self;
}



- (id)copy {
    return self;
}

- (id)mutableCopy {
    return self;
}

// 获取首页数据
- (void)getDataInModule:(RequestModuleType)moduleType
                toalNum:(NSUInteger)toalNum
                success:(void(^)(NSArray<CommonModel *> *models))successBlock
                failure:(FailureBlockType)failureBlock {
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@",BASE_URL];
    [url appendString:@"/api/v1/stl/contents?"];
    [url appendFormat:@"%@",@"apiKey=6de9cc05-6c46-4e29-84f3-a638e442465a"];
    
    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    switch (moduleType) {
        case RequestModuleTypeMagazine:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"商城" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeNews:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"新闻" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeSchool:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"校园" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeStudyAbroad:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"留学" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeJob:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"职场" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeMore:
            [url appendFormat:@"&%@",[NSString stringWithFormat:@"channelName=%@",[@"更多" stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet]]];
            break;
        case RequestModuleTypeSpecialReport:
            url = [@"http://cms.chinacampus.org/api/v1/contents/32?apiKey=6de9cc05-6c46-4e29-84f3-a638e442465a&channelId=36&top=5" mutableCopy];
            break;
            
        default:
            break;
    }
    
    if (toalNum != 0) {
        [url appendFormat:@"%@",[NSString stringWithFormat:@"&totalNum=%ld",toalNum]];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableArray<CommonModel *> *models = [CommonModel mj_objectArrayWithKeyValuesArray:[(NSDictionary *)responseObject objectForKey:@"value"]];
        successBlock(models);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
    }];
}

//  获取购物车
- (void)getshoppingWithAccessToken:(NSString *)accesstoken
                           success:(void(^)(void))successBlock
                           failure:(FailureBlockType)failureBlock {
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiCartGet",SHOPING_URL];
    NSDictionary *params = @{@"siteId":@32};
    
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPRequestSerializer *requestSerializer =  [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //请求头里 添加token
    NSDictionary *headerFieldValueDictionary = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken};
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    manager.requestSerializer = requestSerializer;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
 
}
//  保存购物车
- (void)saveshoppingWithAccessToken:(NSString *)accesstoken
                            success:(void(^)(void))successBlock
                            failure:(FailureBlockType)failureBlock {
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiCartSave",SHOPING_URL];
    NSDictionary *cartinfo =@{@"siteId":@32,@"productId":@"1",@"productName":@"产品1",@"imageUrl":@"",@"linkUrl":@"",@"fee":@2.1,@"isDelivery":@true,@"count":@1,@"addDate":@"2018-06-17 14:18:45"};
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"siteId":@"32",@"cartInfoList":cartinfo};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];

}

//  添加收货地址
-  (void)   addAddressWithAccessToken:(NSString *)accesstoken
                           success:(void(^)(void))successBlock
                           failure:(FailureBlockType)failureBlock {
    

    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiCartSave",BASE_URL];
    NSDictionary *addressInfo = @{@"realName":@"123",@"mobile":@"123",@"tel":@"123",@"location":@"123",@"address":@"123",@"zipCode":@"123",@"isDefault":@false};
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"siteId":@32,@"delivery":@5,@"isEdit":@false,@"addressInfo":addressInfo};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];

    
    
    
}

//  编辑收货地址
-  (void)editAddressWithAccessToken:(NSString *)accesstoken
                            success:(void(^)(void))successBlock
                            failure:(FailureBlockType)failureBlock {
    
    
    
    
}

//  删除收货地址

- (void)removeAddressWithAccessToken:(NSString *)accesstoken
                             success:(void(^)(void))successBlock
                             failure:(FailureBlockType)failureBlock {
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiPayRemoveAddress",BASE_URL];

    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"addressId":@32};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
}

//   新增订单
- (void)neworderWithAccessToken:(NSString *)accesstoken
                        success:(void(^)(void))successBlock
                        failure:(FailureBlockType)failureBlock{
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiPay",BASE_URL];
                            
                        
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"siteId":@32,@"addressId":@37,@"channel":@"app",@"totalFee":@10.1,@"deliveryFee":@1.3,@"totalCount":@1,@"message":@"",@"cartIdList":@[@811],@"isMobile":@true,@"successUrl":@""};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
    
}

//   获取订单
- (void)getorderWithAccessToken:(NSString *)accesstoken
                        success:(void(^)(void))successBlock
                        failure:(FailureBlockType)failureBlock{
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiOrderGet",BASE_URL];
    
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"guid":@"wtE1XnqtFUyzRkzFs7aQ"};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
    
    
}

//   获取全部订单
- (void)getallorderWithAccessToken:(NSString *)accesstoken
                           success:(void(^)(void))successBlock
                           failure:(FailureBlockType)failureBlock{
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiOrderGet",BASE_URL];
    
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
    
}


//   删除订单
- (void)removeorderWithAccessToken:(NSString *)accesstoken
                           success:(void(^)(void))successBlock
                           failure:(FailureBlockType)failureBlock{
    
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@/api/plugins/ss.shopping/ApiOrdersRemove",BASE_URL];
    
    NSDictionary *params = @{@"X-SS-USER-ACCESS-TOKEN":accesstoken,@"orderId":@11};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
        NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorStr);
    }];
    
    
}




@end
